<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件浏览器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            padding: 0;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        .navigation {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .input-section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        .input-section input[type="text"] {
            padding: 8px;
            width: 70%;
            margin-right: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        .input-section button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .input-section button:hover {
            background-color: #45a049;
        }
        .file-table {
            width: 100%;
            border-collapse: collapse;
        }
        .file-table th, .file-table td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        .file-table th {
            background-color: #f2f2f2;
        }
        .file-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .file-table tr:hover {
            background-color: #f1f1f1;
        }
        .download-btn {
            padding: 6px 12px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        .download-btn:hover {
            background-color: #0b7dda;
        }
        .folder {
            color: #FF9800;
            cursor: pointer;
            font-weight: bold;
        }
        .folder:before {
            content: "📁 ";
        }
        .file {
            color: #2196F3;
        }
        .file:before {
            content: "📄 ";
        }
        .indent {
            padding-left: 20px;
        }
        .hidden {
            display: none;
        }
        .error-message {
            color: red;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="navigation">
            <h1>文件浏览器</h1>
            <a href="/upload" class="text-blue-500 hover:text-blue-700 flex items-center">
                <i class="fa fa-upload mr-1"></i> 上传文件
            </a>
        </div>
        
        <div class="input-section">
            <h2>文件搜索</h2>
            <input type="text" id="fileSearch" placeholder="输入搜索关键词...">
            <button id="submitBtn">搜索</button>
            <div id="errorMessage" class="error-message"></div>
        </div>
        
        <div class="file-list-section">
            <h2>搜索结果</h2>
            <table class="file-table">
                <thead>
                    <tr>
                        <th>名称</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="fileTableBody">
                    <!-- 动态内容将在这里渲染 -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
        // 搜索API
        async function searchAPI(query) {
            try {
                const response = await fetch(`/api/search?query=${encodeURIComponent(query)}`);
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }
                return await response.json();
            } catch (error) {
                console.error('搜索API错误:', error);
                showError(`搜索失败: ${error.message}`);
                throw error;
            }
        }

        // 下载文件
        function downloadFile(path, filename) {
            const encodedPath = encodeURIComponent(path);
            const link = document.createElement('a');
            link.href = `/api/download?path=${encodedPath}`;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 渲染文件表格（递归实现）
        function renderFileTable(data, parentPath = '', level = 0) {
            const tableBody = document.getElementById('fileTableBody');
            
            data.forEach(item => {
                // 创建当前行
                const row = document.createElement('tr');
                row.dataset.path = item.path;
                row.dataset.type = item.type;
                if(parentPath) {
                    row.dataset.parent = parentPath;
                    row.classList.add('child-row', 'hidden');
                }
                row.classList.add(item.type === 'folder' ? 'folder-row' : 'file-row');
                
                // 名称列
                const nameCell = document.createElement('td');
                nameCell.className = item.type === 'folder' ? 'folder' : 'file';
                
                // 添加缩进
                const indentSpan = document.createElement('span');
                indentSpan.className = 'indent';
                indentSpan.style.marginLeft = `${level * 20}px`;
                
                if(item.type === 'folder') {
                    const folderSpan = document.createElement('span');
                    folderSpan.textContent = item.name;
                    folderSpan.addEventListener('click', () => toggleFolder(item.path));
                    indentSpan.appendChild(folderSpan);
                } else {
                    const fileSpan = document.createElement('span');
                    fileSpan.textContent = item.name;
                    indentSpan.appendChild(fileSpan);
                }
                
                nameCell.appendChild(indentSpan);
                
                // 操作列
                const actionCell = document.createElement('td');
                if(item.type === 'file') {
                    const downloadBtn = document.createElement('a');
                    downloadBtn.href = '#';
                    downloadBtn.className = 'download-btn';
                    downloadBtn.textContent = '下载';
                    downloadBtn.addEventListener('click', (e) => {
                        e.preventDefault();
                        downloadFile(item.path, item.name);
                    });
                    actionCell.appendChild(downloadBtn);
                } else {
                    actionCell.textContent = '-';
                }
                
                // 组装行
                row.appendChild(nameCell);
                row.appendChild(actionCell);
                
                tableBody.appendChild(row);
                
                // 如果是文件夹且有子项，递归渲染子项
                if(item.type === 'folder' && item.children && item.children.length > 0) {
                    renderFileTable(item.children, item.path, level + 1);
                }
            });
        }

        // 切换文件夹展开/收起
        function toggleFolder(path) {
            const allRows = document.querySelectorAll('#fileTableBody tr');
            
            // 查找所有直接子行
            const childRows = Array.from(allRows).filter(row => 
                row.dataset.parent === path
            );
            
            if (childRows.length === 0) return;
            
            // 检查当前是展开还是收起状态
            const isHidden = childRows[0].classList.contains('hidden');
            
            // 切换所有直接子行的显示状态
            childRows.forEach(row => {
                if (isHidden) {
                    row.classList.remove('hidden');
                } else {
                    row.classList.add('hidden');
                }
            });
        }

        // 显示错误信息
        function showError(message) {
            const errorElement = document.getElementById('errorMessage');
            errorElement.textContent = message;
            setTimeout(() => {
                errorElement.textContent = '';
            }, 5000);
        }

        // 初始化页面
        document.addEventListener('DOMContentLoaded', () => {
            document.getElementById('submitBtn').addEventListener('click', async function() {
                const searchText = document.getElementById('fileSearch').value;
                
                // 清空表格和错误信息
                document.getElementById('fileTableBody').innerHTML = '';
                document.getElementById('errorMessage').textContent = '';
                
                // 显示加载中
                const loadingRow = document.createElement('tr');
                const loadingCell = document.createElement('td');
                loadingCell.colSpan = 2;
                loadingCell.textContent = '搜索中...';
                loadingCell.style.textAlign = 'center';
                loadingRow.appendChild(loadingCell);
                document.getElementById('fileTableBody').appendChild(loadingRow);
                
                try {
                    // 调用API
                    const result = await searchAPI(searchText);
                    
                    // 移除加载中
                    document.getElementById('fileTableBody').innerHTML = '';
                    
                    // 渲染结果
                    if(result.results.length === 0) {
                        const noResultRow = document.createElement('tr');
                        const noResultCell = document.createElement('td');
                        noResultCell.colSpan = 2;
                        noResultCell.textContent = '没有找到匹配的结果';
                        noResultCell.style.textAlign = 'center';
                        noResultRow.appendChild(noResultCell);
                        document.getElementById('fileTableBody').appendChild(noResultRow);
                    } else {
                        renderFileTable(result.results);
                    }
                } catch (error) {
                    // 错误处理在searchAPI中完成
                }
            });
            
            // 初始加载空搜索
            document.getElementById('submitBtn').click();
        });
    </script>
</body>
</html>    